package com.inossem.warehousestorage_inossem.activity.in_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.in_storage.extra.InStorageExtra;
import com.inossem.warehousestorage_inossem.bean.inStorage.InStorageReceiveOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.List;

public class InStorageReceiveMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_EDITTEXT = "0";

    private static final String TYPE_DATEPICKER = "1";

    private static final String TYPE_SELECT = "2";

    private static final String REQUIRED_NO = "0";

    private static final String REQUIRED_YES = "1";

    private static final String TYPE_SERIAL = "serial";

    private static final String TYPE_INDEX = "index";

    private TextView title, serialNumber, materielCode, materielDescription, orderNumber, receivedNumber, factory, demandCompany, inventoryAddress, costObject, objectDescription, pageInfo, showAndHide;

    private EditText inStorageNumber;

    private Button previous, next;

    private String serialNumberStr, unit, mMaterielCode;

    private int index;

    private InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean materielItem;

    private PercentLinearLayout batchLayout;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_in_storage_receive_materiel_detail);
        initView(InStorageReceiveMaterielDetailActivity.this);
        initData(InStorageReceiveMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        orderNumber = (TextView) activity.findViewById(R.id.orderNumber);
        receivedNumber = (TextView) activity.findViewById(R.id.receivedNumber);
        inStorageNumber = (EditText) activity.findViewById(R.id.inStorageNumber);
        factory = (TextView) activity.findViewById(R.id.factory);
        demandCompany = (TextView) activity.findViewById(R.id.demandCompany);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        costObject = (TextView) activity.findViewById(R.id.costObject);
        objectDescription = (TextView) activity.findViewById(R.id.objectDescription);
        pageInfo = (TextView) activity.findViewById(R.id.pageInfo);
        showAndHide = (TextView) activity.findViewById(R.id.showAndHide);
        previous = (Button) activity.findViewById(R.id.previous);
        next = (Button) activity.findViewById(R.id.next);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, R.string.activity_receive_receive_item_title_short, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate(activity);
            }
        });
        inventoryAddress.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                DialogUtils.getReceiveInventoryAddressDialog(activity, InStorageUtils.getReceiveInventoryAddressList(activity), new DialogUtils.ReceiveInventoryAddressListener() {
                    @Override
                    public void onSelect(Dialog dialog, String inventoryAddressValue, String inventoryAddressCode, String factoryValue, String factoryCode) {
                        inventoryAddress.setText(inventoryAddressCode + " - " + inventoryAddressValue);
                    }
                }).show();
            }
        });
        inStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                inStorageNumber.setText("");
            }
        });
        previous.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index > 0) {
                    index--;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index < (InStorageUtils.getReceiveMaterielListSize(activity) - 1)) {
                    index++;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        showAndHide.setOnClickListener((View v) -> {
            if (batchLayout.getVisibility() == View.GONE) {
                batchLayout.setVisibility(View.VISIBLE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_hide_information));
            } else if (batchLayout.getVisibility() == View.VISIBLE) {
                batchLayout.setVisibility(View.GONE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_show_information));
            }
        });
        getExtra(activity);
        getIndexBySerial(activity, serialNumberStr);
        getData(activity, TYPE_SERIAL);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            int indexTemp = InStorageUtils.getReceiveIndexByMaterielCode(activity, mMaterielCode);
            if (indexTemp != -1) {
                if (indexTemp != index) {
                    index = indexTemp;
                    changeAndUpdate(activity);
                }
            } else {
                Utils.middleToast(activity, activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_not_find) + mMaterielCode + activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_materiel));
            }
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        serialNumberStr = activity.getIntent().getStringExtra(InStorageExtra.SERIAL_NUMBER);
    }

    private void getIndexBySerial(Context context, String serialNumber) {
        index = InStorageUtils.getReceiveIndexBySerial(context, serialNumber);
    }

    private void getData(BaseActivity context, String getMaterielInformationFromType) {
        switch (getMaterielInformationFromType) {
            case TYPE_SERIAL:
                materielItem = InStorageUtils.getReceiveMaterielInformationBySerial(context, serialNumberStr);
                break;
            case TYPE_INDEX:
                materielItem = InStorageUtils.getReceiveMaterielInformationByIndex(context, index);
                break;
        }
        unit = materielItem.getUnit();
        serialNumber.setText(materielItem.getSerial());
        materielCode.setText(materielItem.getMaterielCode());
        materielDescription.setText(materielItem.getMaterielDescription());
        orderNumber.setText(materielItem.getOrderNumber() + unit);
        receivedNumber.setText(materielItem.getReceivedNumber() + unit);
        inStorageNumber.setText(TextUtils.isEmpty(materielItem.getRealInStorageNumber()) ? materielItem.getInStorageNumber() : materielItem.getRealInStorageNumber() + unit);
        factory.setText(materielItem.getFactoryCode() + " - " + materielItem.getFactoryValue());
        demandCompany.setText(materielItem.getDemandCompany());
        inventoryAddress.setText(materielItem.getInventoryAddressCode() + " - " + materielItem.getInventoryAddressValue());
        costObject.setText(materielItem.getCostObject());
        objectDescription.setText(materielItem.getObjectDescription());
        batchLayout.removeAllViews();
        List<InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean batchItem = batchList.get(i);
            String type = batchItem.getType();
            boolean required = REQUIRED_YES.equals(batchItem.getRequired()) ? true : false;
            switch (type) {
                case TYPE_EDITTEXT:
                    InStorageUtils.createEditText(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), i + 1);
                    break;
                case TYPE_DATEPICKER:
                    InStorageUtils.createDatePicker(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), i + 1);
                    break;
                case TYPE_SELECT:
                    InStorageUtils.createReceiveSelect(context, batchLayout, batchItem.getName(), required, batchItem.getText(), batchItem.getValue(), batchItem.getSelect(), i + 1);
                    break;
            }
        }
        pageInfo.setText(InStorageUtils.getReceiveMaterielListSize(context) + " | " + (index + 1));
        if (index <= 0) {
            previous.setText(context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_return));
        } else {
            previous.setText(context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_previous));
        }
        if (index >= (InStorageUtils.getReceiveMaterielListSize(context) - 1)) {
            next.setText(context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_return));
        } else {
            next.setText(context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_next));
        }
    }

    private void updateInfo(Context context) {
        materielItem.setRealInStorageNumber(inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim());
        String[] inventoryAddressArray = inventoryAddress.getText().toString().split(" - ");
        materielItem.setInventoryAddressCode(inventoryAddressArray[0]);
        materielItem.setInventoryAddressValue(inventoryAddressArray[1]);
        List<InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean batchItem = batchList.get(i);
            String type = batchItem.getType();
            View view = findViewById(i + 1);
            switch (type) {
                case TYPE_EDITTEXT:
                    batchItem.setText(((EditText) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_DATEPICKER:
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
                case TYPE_SELECT:
                    batchItem.setValue(((TextView) view.findViewById(R.id.value)).getText().toString());
                    batchItem.setText(((TextView) view.findViewById(R.id.text)).getText().toString());
                    break;
            }
        }
        InStorageUtils.updateReceiveInStorageItem(context, materielItem);
    }

    private String check(Context context) {
        String inStorageNumberStr = inStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim();
        if (TextUtils.isEmpty(inStorageNumberStr)) {
            return context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_not_null);
        }

        if (!RegexUtils.checkDecimal(inStorageNumberStr)) {
            return context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_illegal);
        }

        if (!Utils.checkRetainDecimal(inStorageNumberStr, materielItem.getRetainDecimal())) {
            return String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(materielItem.getRetainDecimal()) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : materielItem.getRetainDecimal());
        }

        if (RegexUtils.checkZero(inStorageNumberStr)) {
            return context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_greater_than_zero);
        }

        float maxNumber = Float.parseFloat(materielItem.getInStorageNumber());
        float inStoragetNumberFloat = Float.parseFloat(inStorageNumberStr);
        if (inStoragetNumberFloat > maxNumber) {
            return context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_restriction);
        }

        List<InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean> batchList = materielItem.getBatch();
        for (int i = 0; i < batchList.size(); i++) {
            InStorageReceiveOverviewBean.DataBean.ReceiveInStorageListBean.BatchBean batchItem = batchList.get(i);
            String name = batchItem.getName();
            String type = batchItem.getType();
            String required = batchItem.getRequired();
            if (REQUIRED_YES.equals(required)) {
                View view = findViewById(i + 1);
                if (TYPE_EDITTEXT.equals(type)) {
                    EditText textEditText = (EditText) view.findViewById(R.id.text);
                    if (TextUtils.isEmpty(textEditText.getText().toString())) {
                        return name + context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                } else {
                    TextView textTextView = (TextView) view.findViewById(R.id.text);
                    if (TextUtils.isEmpty(textTextView.getText().toString())) {
                        return name + context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_required_not_null);
                    }
                }
            }
        }
        return null;
    }

    private void backAndUpdate(Context context) {
        String checkResult = check(context);
        if (checkResult == null) {
            updateInfo(context);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + context.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_exit), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    InStorageReceiveMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void changeAndUpdate(BaseActivity activity) {
        String checkResult = check(activity);
        if (checkResult == null) {
            updateInfo(activity);
            getData(activity, TYPE_INDEX);
        } else {
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    getData(activity, TYPE_INDEX);
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate(InStorageReceiveMaterielDetailActivity.this);
    }
}
